package com.zaker.touchtv.modules.login;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.zaker.touchtv.BaseActivity;
import com.zaker.touchtv.R;
import com.zaker.touchtv.utils.Constants;
import com.zaker.touchtv.utils.SystemUtils;

import static com.zaker.touchtv.utils.Constants.LOG_TAG;

public class LoginActivity extends BaseActivity implements LoginWebViewClient.OnLoginListener {

  private WebView mLoginWebView;

  private final LoginWebViewClient mLoginClient = new LoginWebViewClient();

  public static void startLoginActivity(Activity initiatedActivity, int requestCode) {
    Intent intent = new Intent(initiatedActivity, LoginActivity.class);
    initiatedActivity.startActivityForResult(intent, requestCode);
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_layout);
    mLoginWebView = (WebView) findViewById(R.id.login_view);
    SystemUtils.configWebBrowser(getApplicationContext(), mLoginWebView, "");
  }

  @Override
  public void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    if (mLoginWebView != null) {
      mLoginClient.setLoginListener(this);
      mLoginWebView.setWebViewClient(mLoginClient);
      mLoginWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
          Log.i(LOG_TAG, "LoginActivity WebChromeClient onCreateWindow is run");
          return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
        }
      });
      mLoginWebView.loadUrl(Constants.LOGIN_URL);
    }
  }

  @Override
  public void onFinishLoginEvent(String uid, String userName) {
    Intent resultIntent = new Intent();
    resultIntent.putExtra(LoginConstants.LOGIN_RESULT_OF_UID_KEY, uid);
    resultIntent.putExtra(LoginConstants.LOGIN_RESULT_OF_NAME_KEY, userName);
    setResult(LoginConstants.LOGIN_RESULT_CODE, resultIntent);
    finish();
  }

  @Override
  protected void onDestroy() {
    mLoginClient.setLoginListener(null);
    SystemUtils.releaseWebBrowser(mLoginWebView);
    super.onDestroy();
  }
}
